package com.jake.xfeed.recyclerfeed;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;

import java.util.List;

public abstract class BaseFeedDiffCallback<Data> extends DiffUtil.Callback {
    @NonNull
    private final List<Data> oldList;
    @NonNull
    private final List<Data> newList;

    public BaseFeedDiffCallback(@NonNull List<Data> oldList, @NonNull List<Data> newList) {
        this.oldList = oldList;
        this.newList = newList;
    }

    @Override
    public int getOldListSize() {
        return oldList.size();
    }

    @Override
    public int getNewListSize() {
        return newList.size();
    }

    @Override
    public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
        Data oldItem = oldList.get(oldItemPosition);
        Data newItem = newList.get(newItemPosition);
        if (oldItem == null || newItem == null) {
            return false;
        } else {
            return areItemsTheSame(oldItemPosition, oldItem, newItemPosition, newItem);
        }
    }

    /**
     * 判断两个item是否是同一个item，一般只需要判断唯一标识即可，用于更新数据的在adapter中位置（position）信息
     *
     * @param oldItemPosition
     * @param oldItem
     * @param newItemPosition
     * @param newItem
     * @return
     */
    protected abstract boolean areItemsTheSame(int oldItemPosition, @NonNull Data oldItem, int newItemPosition, @NonNull Data newItem);

    /**
     * 判断两个item的内容是否是相同内容，用于决定是否需要调用DataChange
     *
     * @param oldItemPosition
     * @param oldItem
     * @param newItemPosition
     * @param newItem
     * @return
     */
    protected abstract boolean areContentsTheSame(int oldItemPosition, @NonNull Data oldItem, int newItemPosition, @NonNull Data newItem);


    @Override
    public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
        Data oldItem = oldList.get(oldItemPosition);
        Data newItem = newList.get(newItemPosition);
        if (oldItem == null || newItem == null) {
            return false;
        } else {
            return areContentsTheSame(oldItemPosition, oldItem, newItemPosition, newItem);
        }
    }
}
